/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-15 11:23:26
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2024-04-29 10:56:00
 */
/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useEffect, useRef, useState } from 'react'
import { getDictDatasByDictTypes } from '@/api/system/dictData';
import { Button, message, Popconfirm, Space } from 'antd';
import { DictTypeDomain } from '@/type.d/system/dictType';
import ResizeTable from '@/components/ResizeTable';
import { DictDataDomain } from '@/type.d/system';
import { pageInfo } from '@/type.d/ajaxResult';
import PageDiv from '@/components/PageDiv';
import { useStore } from '@/store';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
    ProFormRadio,
    ProFormText,
    QueryFilter
} from '@ant-design/pro-components';
import {
    listDictType,
    delDictType,
    refreshCache,
} from '@/api/system/dictType';
import './index.less';
import DictTypeCard from './dictTypeCard';
import { useNavigate } from 'react-router-dom';

const DictType: React.FC = () => {
    const { layoutStore } = useStore();
    const navigate = useNavigate()

    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<DictTypeDomain>>();
    const [queryValue, setQueryValue] = useState<DictTypeDomain>({});
    const [tableListDataSource, setTableListDataSource] = useState<DictTypeDomain[]>([]);
    const [sysNormalDisableOptions, setSysNormalDisableOptions] = useState<any[]>([]);
    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [cardData, setCardData] = useState<DictTypeDomain>({});
    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');
    const [isedit, setIsedit] = useState<boolean>(false);

    const newdata = { status: '0' }

    /**
     * 列表字段配置
     */
    const columns: ProColumns<DictTypeDomain>[] = [
        {
            title: '主键',
            dataIndex: 'dictId',
            fixed: 'left',
            hideInTable: true
        },
        {
            title: '字典名称',
            dataIndex: 'dictName',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '字典类型',
            dataIndex: 'dictType',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: sysNormalDisableOptions
            },
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            width: 180,
            dataIndex: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: DictTypeDomain) => [
                <a key="data" onClick={() => {
                    onData(entity)
                }}>数据</a>,
                <a key="view" onClick={() => {
                    onView(entity)
                }}>详情</a>,
                <a key="edit" onClick={() => {
                    toCard(entity, true)
                }}>修改</a>,
                <a key="delete">
                    <Popconfirm title="确定要删除数据吗？" okText="是" cancelText="否" onConfirm={() => {
                    onDelete(entity)
                }}>
                    删除
                </Popconfirm>
                </a>
                

            ],
        },
    ];

    const toCard = (data: DictTypeDomain, isEdit: boolean = false) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
        setIsedit(isEdit)
    }

    const onView = (data: DictTypeDomain) => {
        toCard(data)
    }

    const onData = (data: DictTypeDomain) => {
        console.log('navigate', data.dictType);
        navigate(`/system/dictData/${data.dictType}`,{
            state:{
                showname: data.dictName
            }
        });
        // navigate('/system/dictData',{ state: { dictType: data.dictType } });
    }

    const onDelete = (dedata: DictTypeDomain) => {
        if (dedata.dictId) {
            layoutStore.OpenSpanning()
            delDictType(dedata.dictId).then(() => {
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.dictId !== dedata.dictId
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }

    const onRefreshCache = () => {
        layoutStore.OpenSpanning()
        refreshCache().then(()=>{
            message.success('刷新成功！')
        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }


    const headButton = () => {
        return <Space>
            <Button
                size='small'
                key="add"
                type="primary"
                onClick={() => toCard(newdata, true)}
            >
                新增
            </Button>
            <Button
                size='small'
                key="refreshCache"
                type="primary"
                onClick={onRefreshCache}
            >
                刷新缓存
            </Button>
        </Space>
    }

    useEffect(() => {
        layoutStore.OpenSpanning();
        getDictDatasByDictTypes('sys_normal_disable').then((res) => {
            const data = res.data;
            if (data['sysNormalDisable']) {
                const d: [] = data['sysNormalDisable'];
                setSysNormalDisableOptions(d.map((item: DictDataDomain) => {
                    return {
                        label: item.dictLabel,
                        value: item.dictValue,
                    }
                }))

            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }, [])

    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])




    const onQuery = async (_data: any) => {
        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }

        layoutStore.OpenSpanning();
        listDictType({ ..._data, ...pageInfo }).then((res) => {
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };

    
    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,, pageInfo.pageSize])


    return (<PageDiv>{
        pageStatus === 'List' ? <PageDiv>
            <QueryFilter<DictTypeDomain>
                defaultCollapsed
                split
                span={4}
                onFinish={(_data) => onQuery({...pageInfo,..._data,current: 1,})}
                formRef={queryformRef}>
                <ProFormText key='dictName' name="dictName" label="字典名称" />
                <ProFormText key='dictType' name="dictType" label="字典类型" />
                <ProFormRadio.Group key='status' name="status" label="状态" options={sysNormalDisableOptions} />
            </QueryFilter>
            <ResizeTable<DictTypeDomain>
                onRow={record => {
                    return {
                        onDoubleClick: event => {
                            onView(record)
                        },
                    };
                }}
                dataSource={tableListDataSource}
                actionRef={actionRef}
                columns={columns}
                cardBordered
                revalidateOnFocus={false}
                pagination={{
                    ...pageInfo,
                    showTitle: false,
                    onChange: onPageChange
                }}
                headerTitle={headButton()}
                rowKey={"dictId"}
            >
            </ResizeTable>
        </PageDiv> :
            <DictTypeCard
                onBack={() => setPageStatus('List')}
                isedit={isedit}
                setIsedit={setIsedit}
                statusOptions={sysNormalDisableOptions}
                cardData={cardData}
                newdata={newdata}
                tableListDataSource={tableListDataSource}
                setTableListDataSource={setTableListDataSource} />}
    </PageDiv>
    )
}
export default DictType;